interface CardScannerOption {
  finish: Function
}
class CardScanner {
  /**得到的扫码结果 */
  code = ""
  lastTime: number | null = null
  nextTime: number | null = null
  lastCode = ""
  nextCode = ""
  option: CardScannerOption
  constructor(option: CardScannerOption) {
    this.option = option
    document.addEventListener("keypress", this.handleScanner.bind(this))
  }
  destroy() {
    document.removeEventListener("keypress", this.handleScanner.bind(this))
  }
  private handleScanner(e) {
    if (e.key === "Enter") {
      if (this.code.length < 3) {
        console.log(this.code)
        return true
      }
      this.option.finish(this.code)
      return true
    }
    this.nextTime = new Date().getTime()
    this.nextCode = e.key
    if (!this.lastTime && !this.lastCode) {
      this.code += e.key
      console.log(this.code)
    }
    if (this.lastCode && this.lastTime && this.nextTime - this.lastTime > 200) {
      this.code = e.key
      console.log(this.code)
    } else if (this.lastCode && this.lastTime) {
      this.code += e.key
    }
    console.log(this.code)
    this.lastCode = this.nextCode
    this.lastTime = this.nextTime
    return true
  }
}

export default CardScanner
